package com.hmall.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 配置全局的一个拦截器
 */
@Order(-1) //数值越低，优先级越高
@Component
public class AuthorizationFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取Authorization
        exchange.getRequest().mutate().header("authorization", "2").build();

        String authorization = exchange.getRequest().getHeaders().getFirst("authorization");
        ////满足条件放行
        if (StringUtils.isNotBlank(authorization) && StringUtils.equals("2",authorization)){
            return chain.filter(exchange);
        }

        //不满足拦截并异常 HttpStatus.FORBIDDEN 403 权限不足帮我们做一个拦截
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }
}
